<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="所属机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="创建日期" value="createTime" />
          <el-option label="签收日期" value="signDt" />
          <el-option label="调拨日期" value="transDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 170px; margin-right: 2px;">
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="来源" prop="csmTypeSource">
        <el-select v-model="query.csmTypeSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="query.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="query.code" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="query.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="query.code" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="query.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model="query.code" placeholder="请输入" clearable />
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="scoresMerge">积分合并</el-button>
        <el-button type="primary" icon="el-icon-refresh-left" @click="infoCircul">订单流转信息</el-button>
      </div>
      <div>
        <el-select v-model="mode" style="width: 100px;" @change="modeChange">
          <el-option :value="1" label="单选模式" />
          <el-option :value="2" label="多选模式" />
        </el-select>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" />
    <scores-merge ref="scoresMerge" />
    <info-circul ref="infoCircul" />
    <detail ref="detail" />
    <location ref="location" />
  </div>
</template>

<script>
  import { queryDemoTableList } from '@/api'
  import { parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import ScoresMerge from './components/ScoresMerge'
  import Add from './components/Add'
  import InfoCircul from '../components/OrderFlowInfoModal'
  import Detail from './components/Detail'
  import Location from '../components/CsmLocation'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'

  export default {
    name: 'demo',
    components: {
      Add, ScoresMerge, InfoCircul, Detail, Location
    },
    data() {
      return {
        actionColWidth: 80,
        mode: 1,
        treeData: [],
        orderSourceMap: [
          {
            'value': 1,
            'desc': '呼叫中心',
            'key': 'PHONE'
          },
          {
            'value': 2,
            'desc': '微信',
            'key': 'WEIXIN'
          },
          {
            'value': 3,
            'desc': '代客下单',
            'key': 'SUSER'
          },
          {
            'value': 4,
            'desc': '门店',
            'key': 'OTHER'
          },
          {
            'value': 5,
            'desc': '底座',
            'key': 'DZ'
          }
        ],
        dateType: 'createTime',
        date: [],
        csmType: 'csmPhone',
        csmText: '',
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          name: '',
          csmTypeSource: [0],
          code: '',
          roleType: ''
        },
        roleTypeList: [],
        cols: [
          {
            prop: 'name',
            label: '角色名称',
            width: 110
          },
          {
            prop: 'code',
            label: '角色编码',
            width: 110
          }
        ],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        return [
          {
            type: 'expand',
            render: (h, { row }) => {
              return (
                <div>
                  <lb-table
                    ref='lbTable'
                    border
                    element-loading-text='加载中'
                    column={this.cols}
                    data={row.detailList}
                    pagination={false}
                  />
                </div>
              )
            }
          },
          {
            prop: 'name',
            label: '角色名称',
            width: 110
          },
          {
            prop: 'code',
            label: '角色编码',
            width: 110
          },
          {
            prop: 'createUser',
            label: '创建人',
            width: 110
          },
          {
            prop: 'time',
            label: '创建时间',
            width: 150,
            render: (h, { row }) => <span>{ row.time && parseTime(row.time, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'csmPhone',
            label: '客户电话',
            width: 150
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 110
          },
          {
            prop: 'orderCode',
            label: '押金单号',
            width: 150,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openDetail(row)}>{row.orderCode}</el-link>
          },
          {
            prop: 'price',
            align: 'right',
            label: '投保金额'
          },
          {
            prop: 'address',
            label: '投保地址',
            width: 200,
            render: (h, { row }) => <span onClick={() => this.openLocation(row)}><span class='point-span'>{row.lon && <i class='el-icon-location' style='color: #F56C6C;cursor: pointer;'/>}</span>{ row.address }</span>
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-link size='mini' underline={false} onClick={() => this.update(row, $index)}>
                    编辑
                  </el-link>
                  <el-link size='mini' underline={false} onClick={() => this.permission(row)}>
                    权限
                  </el-link>
                  <el-link size='mini' underline={false} type='danger' onClick={() => this.del(row, $index)}>
                    删除
                  </el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    watch: {
      'query.csmTypeSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypeSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypeSource.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypeSource.length === this.orderSourceMap.length) this.query.csmTypeSource = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      await this.getTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query[`${this.dateType}Start`] = moment(this.date[0]).format()
          query[`${this.dateType}End`] = moment(this.date[1]).format()
        }
        query[this.csmType] = this.csmText
        if (this.query.csmTypeSource[0] === 0) query.csmTypeSource = []
        const res = await queryDemoTableList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      async openLocation(row) {
        await this.$refs.location.open(row)
      },
      async add(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      del(row, index) {
        this.$confirm('确定删除此条数据？', '提示', {
          type: 'warning'
        }).then(() => {
          // const loading = this.$message({
          //   message: '正在删除',
          //   duration: 0,
          //   iconClass: 'el-icon-loading'
          // })
          // dicDelete({ id: row.id }).then(() => {
          //   this.tableData.data.splice(index, 1)
          //   this.$notify({
          //     title: '提示',
          //     message: '删除成功',
          //     type: 'success',
          //     duration: 2000
          //   })
          // }).finally(() => {
          //   loading.close()
          // })
        })
      },
      async scoresMerge() {
        await this.$refs.scoresMerge.open()
      },
      async infoCircul() {
        // 参数为订单号
        await this.$refs.infoCircul.open('176697', 1)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 模式选择
      modeChange(value) {
        if (value === 2) {
          this.tableData.column.unshift({
            type: 'selection',
            width: 40
          })
        } else {
          this.tableData.column.shift()
        }
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .el-form-item .el-form-item {
    margin-bottom: 0;
  }
  .merge-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
</style>
